package com.example.springbootblog.controller;


import com.example.springbootblog.model.Result;
import com.example.springbootblog.model.UserInfo;
import com.example.springbootblog.service.UserInfoService;
import com.example.springbootblog.utils.JwtUtils;
import com.example.springbootblog.utils.SecuritUtiles;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    UserInfoService userInfoService;
    @RequestMapping("/login")
    public Result login(String userName, String password) {
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("账号或密码为空!");
        }

        UserInfo userInfo = userInfoService.queryByName(userName);
        // 校验用户合法性
        if(userInfo == null || userInfo.getUserId() <= 0) {
            return Result.fail("用户名或密码错误!");
        }

        // 校验密码是否正确
        if(!SecuritUtiles.verify(password,userInfo.getPassword())) {
            return Result.fail("用户名或密码错误!");
        }
        // 生成令牌
        Map<String,Object> map = new HashMap<>();
        map.put("id",userInfo.getUserId());
        map.put("name",userInfo.getUserName());
        String token = JwtUtils.gentonken(map);

        return Result.success(token);
    }
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) {
        // 从token中拿到用户id
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if(userId == null || userId <= 0) {
            return null;
        }
        UserInfo userInfo = userInfoService.getUserInfo(userId);
        userInfo.setPassword("");
        return userInfo;
    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {
        if(blogId == null || blogId <= 0) {
            return null;
        }
        UserInfo userInfo = userInfoService.getAuthorInfo(blogId);
        if(userInfo == null || userInfo.getUserId() <= 0) {
            return null;
        }
        userInfo.setPassword("");
        return userInfo;
    }
}
